package com.pay.service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.datatype.jsr310.DecimalUtils;
import com.google.common.collect.Lists;
import com.pay.mapper.auto.OmniAddressMapper;
import com.pay.model.auto.OmniAddress;
import com.pay.model.auto.OmniAddressExample;
import com.pay.omni.OmniCoreUtils;
import com.pay.omni.reponse.BtcAddressInfo;
import com.pay.util.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pay.common.base.BaseService;
import com.pay.common.support.Convert;
import com.pay.mapper.auto.OmniTransactionResMapper;
import com.pay.model.auto.OmniTransactionRes;
import com.pay.model.auto.OmniTransactionResExample;
import com.pay.model.custom.Tablepar;
import com.pay.util.SnowflakeIdWorker;

/**
 * omni交易事务Service
 * @Title: OmniTransactionResService.java 
 * @Package com.pay.service 
 * @author fuce
 * @email 87766867@qq.com
 * @date 2019-08-07 13:05:22  
 */
@Slf4j
@Service
public class OmniTransactionResService implements BaseService<OmniTransactionRes, OmniTransactionResExample> {
    @Autowired
    private OmniTransactionResMapper omniTransactionResMapper;
    @Autowired
    private OmniAddressMapper omniAddressMapper;
    @Autowired
    private OmniCoreUtils omniCoreUtils;

    public void updateWalletAndTransactions() throws Exception {
        log.info("-----------充值记录检查开始----------------");
        // 绑定的地址
        List<OmniAddress> list = omniAddressMapper.selectByExample(new OmniAddressExample());
        Map<String, OmniAddress> omniAddressMap = CommonUtils.listToMap(list, "address");
        List<String> addressList = Lists.newArrayList(omniAddressMap.keySet());

        // 获取钱包内比特币地址信息列表
        List<BtcAddressInfo> btcAddressInfos = omniCoreUtils.listReceivedByAddress();
        for(BtcAddressInfo info: btcAddressInfos){
            OmniAddress omniAddress = omniAddressMap.get(info.getAddress());
            if(null == omniAddress){
                continue;
            }
            log.info("地址{}的有效數據是：{}", info.getAddress(), JSON.toJSONString(info));
            // 對比業務
            updateOmniTransactionByTxids(info.getTxids(), omniAddress.getAddress(), addressList);
        }
    }

    /**
     * 检查txids，更新事务
     * @param txids
     * @param address
     * @throws Exception
     */
    public BigDecimal updateOmniTransactionByTxids(List<String> txids, String address, List<String> addressList) throws Exception{
        // 返回值
        BigDecimal result = BigDecimal.ZERO;
        if(null == txids || txids.size() < 1){
            return result;
        }
        // 跟数据库的数据进行比较
        OmniTransactionResExample example = new OmniTransactionResExample();
        example.createCriteria().andReferenceaddressEqualTo(address);
        List<OmniTransactionRes> omniTransactions = omniTransactionResMapper.selectByExample(example);
        Map<String, OmniTransactionRes> transactionResMap = CommonUtils.listToMap(omniTransactions, "txid");
        // 整理出新增的
        OmniTransactionRes dbOmniTransaction;
        OmniTransactionRes omniTransaction;
        for(String txid: txids){
            try {
                dbOmniTransaction = transactionResMap.get(txid);
                // 查询事物
                com.pay.omni.reponse.OmniTransactionRes res = omniCoreUtils.getOmniTransaction(txid);
                if(null == res){
                    continue;
                }
                // 转换对象
                omniTransaction = OmniTransactionRes.builder().build();
                BeanUtils.copyProperties(res, omniTransaction);
                if(null == dbOmniTransaction){
                    omniTransactionResMapper.insert(omniTransaction);
                    continue;
                }
                // 异常数据
                if(null == omniTransaction || addressList.contains(omniTransaction.getSendingaddress())){
                    continue;
                }
                // 更新确认数
                omniTransactionResMapper.updateByPrimaryKeySelective(OmniTransactionRes.builder().confirmations(omniTransaction.getConfirmations()).txid(txid).build());
            } catch (Exception e){
                log.info(e.getMessage());
            }
        }
        return result;
    }

    /**
     * 分页查询
     * @param tablepar
     * @param name
     * @return
     */
    public PageInfo<OmniTransactionRes> list(Tablepar tablepar, String name) {
            OmniTransactionResExample testExample = new OmniTransactionResExample();
        testExample.setOrderByClause("blocktime desc");

        PageHelper.startPage(tablepar.getPageNum(), tablepar.getPageSize());
        List<OmniTransactionRes> list = omniTransactionResMapper.selectByExample(testExample);
        PageInfo<OmniTransactionRes> pageInfo = new PageInfo<OmniTransactionRes>(list);
        return pageInfo;
    }

            @Override
        public int deleteByPrimaryKey(String ids) {
            List<String> lista = Convert.toListStrArray(ids);
                OmniTransactionResExample example = new OmniTransactionResExample();
            example.createCriteria().andTxidIn(lista);
            return omniTransactionResMapper.deleteByExample(example);
        }


        @Override
        public OmniTransactionRes selectByPrimaryKey(String id) {

            return omniTransactionResMapper.selectByPrimaryKey(id);
        }


        @Override
        public int updateByPrimaryKeySelective(OmniTransactionRes record) {
            return omniTransactionResMapper.updateByPrimaryKeySelective(record);
        }

    /**
     * 添加
     */
    @Override
    public int insertSelective(OmniTransactionRes record) {
        //添加雪花主键id
        record.setTxid(SnowflakeIdWorker.getUUID());
        return omniTransactionResMapper.insertSelective(record);
    }


    @Override
    public int updateByExampleSelective(OmniTransactionRes record, OmniTransactionResExample example) {

        return omniTransactionResMapper.updateByExampleSelective(record, example);
    }


    @Override
    public int updateByExample(OmniTransactionRes record, OmniTransactionResExample example) {

        return omniTransactionResMapper.updateByExample(record, example);
    }

    @Override
    public List<OmniTransactionRes> selectByExample(OmniTransactionResExample example) {

        return omniTransactionResMapper.selectByExample(example);
    }


    @Override
    public long countByExample(OmniTransactionResExample example) {

        return omniTransactionResMapper.countByExample(example);
    }


    @Override
    public int deleteByExample(OmniTransactionResExample example) {

        return omniTransactionResMapper.deleteByExample(example);
    }

    /**
     * 检查name
     * @param omniTransactionRes
     * @return
     */
    public int checkNameUnique(OmniTransactionRes omniTransactionRes) {
            OmniTransactionResExample example = new OmniTransactionResExample();
        List<OmniTransactionRes> list = omniTransactionResMapper.selectByExample(example);
        return list.size();
    }


}
